import re

from django.contrib.auth.backends import ModelBackend # 用户登录的认证

# 自定义登录返回数据
from users.models import User


def jwt_response(token, user=None, request=None):
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


def get_user_by_account(account):
    """
    根据 这个账户--account
    :param account: 判断是否为用户名或者是手机号
    :return: user  对象
    """
    #  查询模型类对象
    try:
        if re.match('^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            #
            user = User.objects.get(username=account)

    except:
        return None
    else:
        return user


class UsernameModelBackend(ModelBackend):
    """
    自定义用户名和手机号登录方法
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        #  用户对象
        user = get_user_by_account(username)
        #
        if user.check_password(password) and user is not None:
            return user
